#include "musiclist.h"


MusicList::MusicList()
{
    musicList.clear();
}

void MusicList::addMusicsByUrl(const QList<QUrl> &urls)
{
    for(auto e:urls)
    {
        //qDebug()<<"void MusicList::addMusicsByUrl(const QList<QUrl> &urls) start";
        QString musicPath=e.toLocalFile();
        if(musicPaths.contains(musicPath))
        {
            continue;
        }
        musicPaths.insert(musicPath);
        QMimeDatabase mimeDb;
        QMimeType mimeType=mimeDb.mimeTypeForFile(e.toLocalFile());
        QString mime=mimeType.name();
        //qDebug()<<"mime: "<<mime;
        if(mime=="audio/mpeg"||mime=="audio/flac"||mime=="audio/wav")
        {
            //qDebug()<<"解析音乐";
            Music music(e);
            musicList.push_back(music);
        }
    }
}

QVector<Music> MusicList::getMusicList()
{
    return this->musicList;
}

iterator MusicList::begin()
{
    return musicList.begin();
}

iterator MusicList::end()
{
    return musicList.end();
}

iterator MusicList::findMusicByMusicId(const QString &musicId)
{
    for(auto it=begin();it!=end();it++)
    {
        if(it->getMusicId()==musicId)
            return it;
    }
    return end();
}

void MusicList::removeMusicByMusicid(const QString &musicId)
{
    qDebug()<<"void MusicList::removeMusicByMusicid(const QString &musicId)";
    for(auto it=begin();it!=end();it++)
    {
        if(it->getMusicId()==musicId)
        {
            qDebug()<<it->getMusicName();
            this->musicList.erase(it);
            break;
        }
    }
}

void MusicList::writeMusicToDB()
{
    for(auto music:musicList)
    {
        music.insertMusicToDB();
    }
}

void MusicList::readMusicFromDB()
{
    QSqlQuery query;
    query.prepare("SELECT musicId,musicName,musicSinger,musicCover,musicUrl,duration,isLike,isHistory FROM musicInfo");
    if(!query.exec())
    {
        qDebug()<<"读取数据库失败:"<<query.lastError().text();
        return;
    }
    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setMusicSinger(query.value(2).toString());
        music.setMusicCover(query.value(3).toString());
        music.setMusicUrl("file:///"+query.value(4).toString());
        music.setDuration(query.value(5).toLongLong());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());

        musicList.push_back(music);

        musicPaths.insert(music.getMusicUrl().toLocalFile());
    }

    qDebug()<<"读取数据库成功";
}














